import Consts from '@/src/consts.js'
import request from '@/src/utils/request.js'

/**
 * 在App.vue中onLaunch中调用这个方法
 * @param {(payload) => void} handler
 */
export const monitorPush = handler => {
  // #ifdef APP-PLUS
  plus.push.clear()
  const _handlePush = function(message, source) {
    const { globalData } = getApp()
    if (!globalData || globalData.isBackground == null) {
      uni.showModal({
        content: '使用推送，请在App.vue中定义globalData.isBackground，然后在对应的应用生命周期中，改变这个bool值'
      })
      return
    }
    if (globalData.isBackground) {
      // App处于后台时，iOS收到推送，从消息中心弹出推送，此时还未点击推送消息
      // 就自动触发了click事件，从而执行到这里 这个是框架的一个bug
      console.log(`${source}推送，但app处于后台，为避免触发2次，忽略掉此次触发`)
      return
    }
    let isAndroid = message.__UUID__ && /^android/i.test(message.__UUID__)
    console.log(`是否是安卓推送：${isAndroid}`)
    let payload = message.payload
    if (typeof payload === 'string') {
      payload = JSON.parse(decodeURIComponent(payload))
    }
    console.log(`payload: ${payload}`)
    if (payload.__local) {
      console.log(`收到本地推送：${decodeURIComponent(JSON.stringify(message))},直接返回`)
      return
    }
    if (handler) {
      handler(payload)
    }
    if (isAndroid) {
      // 如果是安卓的话 因为使用透传模板，推送消息不会出现在通知栏中，需要主动创建一个本地消息
      plus.push.createMessage(payload.content, JSON.stringify({ __local: true }))
    }
  }
  plus.push.addEventListener('click', function(message) {
    console.log('click message: ', message)
    _handlePush(message, 'click')
  })
  plus.push.addEventListener('receive', function(message) {
    console.log('receive message: ', message)
    _handlePush(message, 'receive')
  })
  // #endif
}

/**
 * 获取推送的clientid(ci)
 */
export const getClientId = () => {
  // #ifdef APP-PLUS
  return new Promise((resolve, reject) => {
    let retryCount = 6
    let timer = null
    timer = setInterval(() => {
      let info = plus.push.getClientInfo()
      if (retryCount === 0 || (info && info.clientid)) {
        const value = (info && info.clientid) || ''
        resolve(value)
        return timer && clearInterval(timer)
      }
      retryCount--
    }, 1000)
  })
  // #endif
}

/**
 * 绑定推送的cid与codeid
 */
export const bindCodeid = async codeid => {
  if (!Consts.PUSH || !Consts.PUSH.BIND) {
    uni.showModal({
      content: '请在@src/consts.js中设置PUSH.BIND常量，具体含义参考@/src/basic/consts.js'
    })
    return
  }
  const clientid = await getClientId()
  if (clientid) {
    const { head: { ret = -1 } = {} } = await request.get(Consts.PUSH.BIND, {
      codeid,
      clientid
    })
    return ret === 0
  } else {
    console.log('uni-push-bind:获取clientid失败')
    return false
  }
}

export const unbindCodeid = async codeid => {
  if (!Consts.PUSH || !Consts.PUSH.UNBIND) {
    uni.showModal({
      content: '请在@src/consts.js中设置PUSH.UNBIND常量，具体含义参考@/src/basic/consts.js'
    })
    return
  }
  const clientid = await getClientId()
  if (clientid) {
    const { head: { ret = -1 } = {} } = await request.get(Consts.UNBIND, {
      codeid,
      clientid
    })
    return ret === 0
  } else {
    console.log('uni-push-unbind:获取clientid失败')
    return false
  }
}
